package seleniumdemo.common.driver;

import lombok.Data;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author guoying
 * @version 1.0
 * @date 2021/8/1 17:10
 */
@Data
public class Wait {

    //等待时间,默认单位为秒
    private int waitTime;

    /** 等待方式:
     * implicitlyWait  隐式等待
     * driverWait  显式等待
     */
    private String waitType;

    //driver
    private DriverBase driverBase;

    //显式等待
    private WebDriverWait webDriverWait;


    public Wait(int time,String waitType,DriverBase driverBase){
        this.driverBase=driverBase;
        this.waitTime=time;
        this.waitType=waitType;
        if(("implicitlyWait").equals(waitType)){
            driverBase.getDriver().manage().timeouts().implicitlyWait(time, TimeUnit.SECONDS);
        }else if(("driverWait").equals(waitType)){
            //实例化一个显式等待(等待元素出现,超时时间5秒)
            this.webDriverWait=new WebDriverWait(driverBase.getDriver(),time);

        }else {
            //不想抛异常,暂时输出控制台便可
            System.out.println("等待类型输入错误!");
            new Exception("等待类型输入错误!");
        }

    }

    //隐式等待元素是否可以点击
    public WebElement driverWaitClick(By by){
        WebElement result=this.webDriverWait.until(ExpectedConditions.elementToBeClickable(by));
        return result;

    }

    //隐式等待元素是否是否被加载在DOM中
    public WebElement driverWaitLocated(By by){
        WebElement result=this.webDriverWait.until(ExpectedConditions.presenceOfElementLocated(by));
        return result;

    }


    //隐式等待判断指定的元素是否被选中
    public Boolean driverWaitSelected(By by){

       boolean result= this.webDriverWait.until(ExpectedConditions.elementSelectionStateToBe(by,true));

        return result;

    }

    //隐式等待判断页面标题是否符合预期
    public Boolean titleIs(String title){
        boolean result=this.webDriverWait.until(ExpectedConditions.titleIs(title));
        return result;
    }


    //visibilityOfAllElementsLocatedBy( By locator)
    //隐式等待判断页面元素是否可见
    public WebElement visibility(By by){
        WebElement result=this.webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(by));
        return result;
    }

    //textToBePresentInElement( WebElement element,  String text)
    //隐式等待判断页面元素的text是否符合预期
    public Boolean textIs(By by,String text){

        Boolean result = this.webDriverWait.until(ExpectedConditions.textToBePresentInElement(by, text));
        return result;
    }


}
